package com.leruan.aasimp.action.forum;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.leruan.aasimp.entity.Forumuser;
import com.leruan.aasimp.service.ForumUserService;
import com.leruan.aasimp.util.Validators;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
    /**
     * 
     */
    private static final long serialVersionUID = 7875880523510015730L;
    @Resource
    private ForumUserService forumUserService;

    public String login() {
        Forumuser forumuser = (Forumuser) ActionContext.getContext().getSession().get("user");
        if (null != forumuser) {
            addActionError("您还没有登录，请先登录");
            return "wrong";
        }
        HttpServletRequest request = ServletActionContext.getRequest();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (Validators.isEmpty(username) || Validators.isEmpty(password)) {
            return "wrong";
        }
        forumuser = forumUserService.getForumUserByUsernameAndPassword(username, password);
        if (null == forumuser) {
            addActionError("用户名或密码有误");
            return "wrong";
        }
        else {
            request.getSession().setAttribute("user", forumuser);
            return "success";
        }
    }

    public String logout() {
        HttpServletRequest request = ServletActionContext.getRequest();
        request.getSession().removeAttribute("user");
        request.getSession().invalidate();
        return "success";
    }

    public String loginOnly() {
        HttpServletRequest request = ServletActionContext.getRequest();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Forumuser forumuser = forumUserService.getForumUserByUsernameAndPassword(username, password);
        System.out.println(forumuser + "+++++++++++");
        if (null == forumuser) {
            addActionError("用户名或密码有误");
            return "wrong";
        }
        else {
            request.getSession().setAttribute("user", forumuser);
            return "success";
        }
    }

    public ForumUserService getForumUserService() {
        return forumUserService;
    }

    public void setForumUserService(ForumUserService forumUserService) {
        this.forumUserService = forumUserService;
    }

}
